import {
  request
} from "../../request/index.js";
import {
  getUserProfile,
  login,
  getSetting,
  openSetting,
  chooseAddress
} from "../../utils/asyncWx.js";
// pages/user/user.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    hasUserInfo: false,
    collectNum: 0,
    historyNum: 0
  },

  onShow: function () {
    const userInfo = wx.getStorageSync('userInfo') || {};
    let hasUserInfo = false;
    if (userInfo.nickName) {
      //1000*60*60*24*7 => 7天
      if (Date.parse(new Date()) / 1000 - userInfo.watermark.timestamp < 1000 * 60 * 60 * 24 * 7) {
        hasUserInfo = true;
        const collectNum = wx.getStorageSync('collect').length;
        const historyNum = wx.getStorageSync('history').length;
        this.setData({
          userInfo,
          hasUserInfo,
          collectNum,
          historyNum
        });
      } else {
        wx.setStorageSync('userInfo', {});
      }
    }
  },

  async handleLogin() {
    // 获取权限 判断用户是否授予权限
    const res1 = await getSetting();
    const scopeAddress = res1.authSetting["scope.userInfo"];
    // 未授予权限 打开设置引导用户授予权限
    if (!scopeAddress) {
      await openSetting();
      return;
    }
    // 获取用户信息
    const {
      encryptedData,
      rawData,
      iv,
      signature,
      userInfo
    } = await getUserProfile();
    // 获取小程序登录成功后的code
    const {
      code
    } = await login();
    const loginParams = {
      encryptedData,
      rawData,
      iv,
      signature,
      code
    };
    // 发送请求 获取用户的token
    const res = await request({
      url: "/users/wxlogin",
      data: loginParams,
      method: "POST"
    });
    // 没有token 没有企业账号无法获取token
    // 假装有token 将token存入缓存中 同时跳转回上一个页面
    const token = res.token || "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo";
    const collectNum = wx.getStorageSync('collect').length;
    const historyNum = wx.getStorageSync('history').length;
    // 将用户信息设置到data
    this.setData({
      userInfo,
      hasUserInfo: true,
      collectNum,
      historyNum
    });
    wx.setStorageSync('userInfo', userInfo);
    wx.setStorageSync('token', token);
  },
  // 头像预览
  handlePreviewImage() {
    const {
      avatarUrl
    } = wx.getStorageSync('userInfo');
    wx.previewImage({
      urls: [avatarUrl]
    });
  },
  // 地址管理
  async handleChooseAddress() {
    try {
      // 获取权限状态的
      const res1 = await getSetting()
      const scopeAddress = res1.authSetting["scope.address"]
      if (scopeAddress === false) {
        // 用户 以前 拒绝过授予权限，先引导用户授予权限
        await openSetting()
      }
      let address = await chooseAddress()
      // 把地址存入本地存储
      address.allAddresss = address.cityName + address.countyName + address.detailInfo
      wx.setStorageSync('address', address)

    } catch (error) {
      console.log(error)
    }
  }
})